//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	MetaFields.cs
//  Developer:	Solomatov Igor
//  Created:	15.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace Smart.Common
{
	/// <summary>
	/// Store field metadata
	/// </summary>
	[DebuggerDisplay("MetaFields Name={Name} Title={Title}")]
	public abstract class MetaFields
	{
		/// <summary>
		/// List or Name
		/// </summary>
		public string Name { get; set; }

		/// <summary>
		/// All field IDs
		/// </summary>
		public Dictionary<string, Guid> FieldIDs { get; set; }

		/// <summary>
		/// All fields
		/// </summary>
		public Dictionary<Guid, MetaField> Fields { get; set; }

		/// <summary>
		/// Initializes a new instance of the <see cref="T:Smart.Common.MetaFields"/> class.
		/// </summary>
		protected MetaFields(string name)
		{
			Name = name;

			FieldIDs = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase);
			Fields = new Dictionary<Guid, MetaField>();
		}

		/// <summary>
		/// Fill cache info
		/// </summary>
		public abstract void LoadFields(object source);

		/// <summary>
		/// Return MetaField by TitleOrName
		/// </summary>
		public virtual MetaField Field(string titleOrName)
		{
			var id = FieldIDs.SafeGet(titleOrName);

			var res = (id == Guid.Empty ? null : Fields.SafeGet(id));

			if (res == null)
			{
				H.LT("MetaFields:Field.2 Exception: field '{0}' not found at '{1}'!", titleOrName, Name);
			}

			return res;
		}

		/// <summary>
		/// Return MetaField by Id
		/// </summary>
		public virtual MetaField Field(Guid id)
		{
			var res = (id == Guid.Empty ? null : Fields.SafeGet(id));

			if (res == null)
			{
				H.LT("MetaFields:Field.3 Exception: field '{0}' not found at '{1}'!", id, Name);
			}

			return res;
		}

		/// <summary>
		/// Return field name by TitleOrName
		/// </summary>
		public virtual string FieldName(string titleOrName)
		{
			if (titleOrName.IsNullOrEmpty())
				return titleOrName;

			var mf = Field(titleOrName);

			return (mf == null ? "_ERROR_FIELD_NOT_FOUND_" : mf.Name);
		}

		/// <summary>
		/// Return field name by Id
		/// </summary>
		public virtual string FieldName(Guid id)
		{
			var mf = Field(id);

			return (mf == null ? "_ERROR_FIELD_NOT_FOUND_" : mf.Name);
		}

		/// <summary>
		/// Return field id by TitleOrName
		/// </summary>
		public virtual Guid FieldId(string titleOrName)
		{
			if (titleOrName.IsNullOrEmpty())
				return Guid.Empty;

			var mf = Field(titleOrName);

			return (mf == null ? Guid.Empty : mf.ID);
		}
	}
}